import json

from django.core.paginator import Paginator
from django.http import JsonResponse
from django.views import View

from price.models import Price, PriceSerializer


# 新增或修改
class SaveView(View):
    def post(self, request):
        try:
            data = json.loads(request.body.decode('utf-8'))
            if data['id'] == -1:  # 添加
                obj = Price(name=data['name'], unit=data['unit'], value=data['value'],
                            source=data['source'], remark=data['remark'])
                obj.save()
            else:  # 修改
                obj = Price(id=data['id'], name=data['name'], unit=data['unit'], value=data['value'],
                            source=data['source'], remark=data['remark'])
                obj.save()
            return JsonResponse({'code': 200, 'msg': '执行成功！'})
        # 捕获其他未预料的异常（作为兜底）
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'msg': f'服务器错误：{str(e)}'  # 生产环境可简化为"服务器内部错误"
            })



# 信息查询
class SearchView(View):
    def post(self, req):
        try:
            data = json.loads(req.body.decode('utf-8'))

            pageNum = data['pageNum']  # 当前页
            pageSize = data['pageSize']  # 每页大小
            query = data['query']  # 查询参数

            # 获取查询集
            queryset = Price.objects.filter(name__icontains=query)
            total = queryset.count()

            # 分页
            paginator = Paginator(queryset, pageSize)
            dataPage = paginator.page(pageNum)

            # 序列化数据 - 传递查询集给序列化器
            serializer = PriceSerializer(dataPage.object_list, many=True)

            return JsonResponse({'code': 200, 'data': serializer.data, 'total': total})
        # 捕获其他未预料的异常（作为兜底）
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'msg': f'服务器错误：{str(e)}'  # 生产环境可简化为"服务器内部错误"
            })